using System;
using System.Web;

namespace Framework.Library.Core.Utils.Web.Modules
{
    public class DefaultRedirectModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += context_BeginRequest;
        }

        #endregion

        private void context_BeginRequest(object sender, EventArgs e)
        {
            var application = (HttpApplication) sender;
            HttpContext context = application.Context;
            HttpRequest request = context.Request;

            string pageName = VirtualPathUtility.GetFileName(request.Path);

            if (string.Compare(pageName, "default.aspx", StringComparison.OrdinalIgnoreCase) == 0 &&
                request["iisdefault"] != "true")
            {
                string path = VirtualPathUtility.GetDirectory(request.Path);
                string query = request.Url.Query;

                ResponseUtils.PermanentRedirect(context.Response, path + query);
            }
        }
    }
}